﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Protocol.Interface
{
    public delegate void AcceptEventHandler(TcpClient client);
    public delegate void ErrorEventHandler(Exception e, ErrorType type);
    public delegate void ReceiveEventHandler(TcpClient client, string msg);
    /// <summary>
    /// 异步服务端
    /// </summary>
    public interface IAsyncServer
    {

        /// <summary>
        /// 当服务端在等待连接/接收或发送出现错误时触发事件
        /// </summary>
        event ErrorEventHandler OnError;
        /// <summary>
        /// 当服务端接收到客户端连接时时触发事件
        /// </summary>
        event AcceptEventHandler OnAccept;
        /// <summary>
        /// 当服务端接收到消息时触发事件
        /// </summary>
        event ReceiveEventHandler OnReceive;
        /// <summary>
        /// 服务器
        /// </summary>
        TcpListener Server { get; }
        /// <summary>
        /// 接收以及写入的编码
        /// </summary>
        Encoding _Encoding { get; set; }
        /// <summary>
        /// 运行状态
        /// </summary>
        bool Running { get; }
        /// <summary>
        /// 服务端的端口
        /// </summary>
        int Port { get; }

        /// <summary>
        /// 启动服务器
        /// </summary>
        /// <returns></returns>
        Task Start();
        /// <summary>
        /// 停止服务器
        /// </summary>
        void Stop();
        /// <summary>
        /// 断开指定客户端连接
        /// </summary>
        /// <param name="ip"></param>
        void Disconnect(IPEndPoint ip);
        /// <summary>
        /// 向指定客户端发送数据
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="msg"></param>
        void Send(IPEndPoint ip, string msg);
        /// <summary>
        /// 向指定客户端发送数据(异步)
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        Task SendAsync(IPEndPoint ip, string msg);
    }

    public enum ErrorType
    {
        ConnectError,
        ReceiveError,
        SendError
    }
}
